let qrCodeContainer;
let qrCodeIcon;
let isQRCodeVisible = false;

function createQRCodeIcon() {
  qrCodeIcon = document.createElement('div');
  qrCodeIcon.id = 'qr-code-icon';
  qrCodeIcon.innerHTML = '🔳'; // 使用一个简单的 emoji 作为图标
  qrCodeIcon.style.cursor = 'pointer';
  document.body.appendChild(qrCodeIcon);

  qrCodeIcon.addEventListener('click', toggleQRCode);
}

function toggleQRCode() {
  if (isQRCodeVisible) {
    qrCodeContainer.style.display = 'none';
    isQRCodeVisible = false;
  } else {
    if (!qrCodeContainer) {
      createQRCodeContainer();
    }
    qrCodeContainer.style.display = 'block';
    createQRCode(window.location.href);
    isQRCodeVisible = true;
  }
}

function createQRCodeContainer() {
  qrCodeContainer = document.createElement('div');
  qrCodeContainer.id = 'url-qrcode-container';
  qrCodeContainer.style.display = 'none';
  document.body.appendChild(qrCodeContainer);
}

function createQRCode(url) {
  if (!url) {
    console.error('Cannot create QR code: URL is undefined');
    return;
  }

  qrCodeContainer.innerHTML = '';
  try {
    new QRCode(qrCodeContainer, {
      text: url,
      width: 128,
      height: 128
    });
  } catch (error) {
    console.error('Error creating QR code:', error);
  }
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === "updateQRCode") {
    if (request.url && isQRCodeVisible) {
      createQRCode(request.url);
    }
  }
});

createQRCodeIcon();